<?php
namespace api\modules\v1\controllers;

use common\bonus\BaseBonus;
use common\models\Balance;
use common\models\BalanceLog;
use common\models\GroupActivity;
use common\models\GroupDetail;
use common\models\GroupFinalist;
use common\models\GroupWinning;
use common\models\Member;
use common\models\StaticInstance;
use common\models\TradeCommodity;
use common\models\TradeOrder;
use yii\debug\models\search\Log;

/**
 *拼团活动
 * 2020/08/08
 * gonglei
 */

class GroupController extends CoreController
{
    /**
     * 参加拼团活动
     *
     */
    public function actionSetGroup(){
        $arr['member_id']    = $this->_memberId;
        $arr['commodity_id']     = $this->request('commodity_id');

     if(!$this->_member['state']) $this->error('你暂不能此操作');
  
        if (!$arr['commodity_id'])
            $this->error('请选择拼团活动');

        if ($this->_member['paypwd'] !== md5($this->request('password')))
            $this->error('密码有误');

        $times    = strtotime('12:00');
        $time_now = strtotime(date('H:i',time()));

        if ($times<$time_now)
            $this->error('该拼团活动只限12点前参加');

        /*判断该活动是否过期*/

        $where = 'commodity_id='.$arr['commodity_id'].' and sell_end_time >="'.date('Y-m-d',time())
            .'" and sell_start_time<="'.date('Y-m-d',time()).'" and type=3';

        $groupDara  = TradeCommodity::getOne($where);
        if (!$groupDara)  $this->error('该活动暂不能参加');

        /*判断该用户今天是否已经参加过活动*/
      $where = 'commodity_id ='.$arr['commodity_id']." 
      and group_time ='".date('Y-m-d')."'
      and member_id REGEXP '^".$this->_memberId.",|,"
      .$this->_memberId.",|,".$this->_memberId."$'";
      
        $checkUser = GroupDetail::getOne($where);

        if ($checkUser) $this->error('该活动您今天已参与');

          $data1 = StaticInstance::find()->where(['order_type'=>[1,2],
            'member_id'=>$arr['member_id'],'status'=>1,'in_num'=>$groupDara['money_up']])->asarray()->all();
            
        if (!$data1) {

          $this->error('参加拼团活动前必须签约同等价值的合约');
        }


        try {
            $transaction = \Yii::$app->db->beginTransaction();
            /*满足条件,生成拼团活动数据*/
            $groupDetail = new GroupDetail();
            $re          = $groupDetail->userSetGroup($groupDara, $this->_member);

            //扣除账本
            $res = Balance::reduceBalance($arr['member_id'],1,$groupDara['money_up'],6,$re,'',1);
            if (isset($res['state']) && $res['state']==false) throw new \Exception($res['msg']);

            $transaction->commit();
            $this->out('参加成功');
        }catch (\Exception $e)
        {
            $transaction->rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     *取消拼团活动
     *
     */
    public function actionCancelGroup(){
        $arr['member_id']           = $this->_memberId;
        $arr['group_detail_id']     = $this->request('group_detail_id');
        if (!$arr['group_detail_id'])
            $this->error('请选择拼团活动');

        $times    = strtotime('12:00');
        $time_now = strtotime(date('H:i','08:00'));

        if ($times<$time_now)
            $this->error('该拼团活动只限12点前退团');

        $where       = 'group_detail_id='.$arr['group_detail_id'];
        $groupDetail = new GroupDetail();
        $groupDara   = GroupDetail::getOne($where,'*');

        if (!$groupDara)  $this->error('该活动暂不能退团');
        $memberArr   = explode(',',$groupDara['member_id']);
        if (!in_array($arr['member_id'],$memberArr)) $this->error('该活动不能退团');
        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $re          = $groupDetail->userCancelGroup($groupDara, $arr['member_id']);
            //增加余额
            $res = Balance::addBalance($arr['member_id'],1,$groupDara['group_money'],6,$groupDara['group_detail_id'],$from='');

            if (isset($res['state']) && $res['state']==false) throw new \Exception($res['msg']);
            $transaction->commit();
            $this->out('操作成功');
        }catch (\Exception $e)
        {
            $transaction->rollback();
            $this->error($e->getMessage());
        }

    }

    /**
     * 我的拼团列表
     *
     */
    public function actionGroupList(){
        $whereArr = $this->formartWhere();

        $params = array(
            'field'	=> ['*'],
            'order' => 'create_time desc',
            'page'	=> $this->request('page',1),
            'limit' => $this->request('page_size',10),
            'member_id'=>$this->_memberId,
        );

        $data  = GroupDetail::dataList($whereArr,$params,['winning']);
        $count = GroupDetail::$pages;
        $this->out('拼团列表',$data,['count'=>$count]);
    }

    /**
     * 我的入围
     *
     */
    public function actionGroupFinalist(){

        $whereArr = $this->formartWhere();

        $params = array(
            'field'	=> ['*'],
            'order' => 'create_time desc',
            'page'	=> $this->request('page',1),
            'limit' => $this->request('page_size',10),
            'member_id'=>$this->_memberId,
        );
        if ($params['member_id']){
            $whereArr['where']=['member_id'=>$this->_memberId];
        }
        $data  = GroupFinalist::dataList($whereArr,$params,['ruwei']);
        $count = GroupFinalist::$pages;
        $this->out('拼团列表',$data,['count'=>$count]);
    }

    /*
    *列表 条件组装
    */
    public function formartWhere()
    {
        $where = [];
        $whereAnd = [];
        if (!$this->request('search')){
            return [];
        }
        $searchKeys = json_decode($this->request('search'),1);
        foreach($searchKeys as $k=>$val)
        {
            if($val=='') continue;
            if($k=='date')
            {
                if(!$val['0'] || !$val['1']) continue;
                $whereAnd[] = ['between', 'create_time', strtotime($val[0]),strtotime($val[1])];
            }else
            {
                $where[$k] = $val;
            }
        }
        return array('where'=>$where,'whereAnd'=>$whereAnd);
    }

    /**
     * 中奖列表
     */
    public function actionWinningList(){

        $whereArr = $this->formartWhere();
        $time     = $this->request('time','12:00');
        $startTime = date('Y-m-d '.$time,time());

        if (time()<strtotime($startTime)){

            $this->out('中奖列表',[],['count'=>0]);
        }
        $whereArr['where'] ="winning_time='".$startTime."'";
        $params = array(
            'field'	=> '*',
            'page'	=> $this->request('page',1),
            'limit' => $this->request('page_size',10),
        );
        $data  = GroupWinning::dataList($whereArr,$params);
        $count = GroupWinning::$pages;
        $this->out('中奖列表',$data,['count'=>$count]);
    }


    public function actionWinningUser(){



        $startTime = date('Y-m-d 00:00:00',time());
        $endTime   = date('Y-m-d H:i:s',time());
        $memberId  = $this->_memberId;
        $where ="winning_time>='".$startTime."' and winning_time<='".$endTime."' and  member_id=$memberId";

        $data  = GroupWinning::getAll($where);
        $this->out('中奖',$data);
    }

    /**
     * 拼团签约  USDT转UPH
     *
     */
    public function actionGroupCommodity(){
        $arr['member_id']    = $this->_memberId;
        $arr['goods_id']     = $this->request('commodity_id'); //活动表ID
        $arr['winning_id']   = $this->request('winning_id');  //拼团成功表ID

        if (!$arr['goods_id'])
            $this->error('请选择投资项目');
        $where = 'commodity_id='.$arr['goods_id'].' and sell_end_time >="'.date('Y-m-d',time())
            .'" and sell_start_time<="'.date('Y-m-d',time()).'" and type=3';

        if (!$arr['winning_id']) $this->error('传参有误请检查');

        $data  = TradeCommodity::getOne($where);
        if (!$data) $this->error('项目不存在');

        $wingingArr = GroupWinning::getOne(['id'=>$arr['winning_id'],'member_id'=>$arr['member_id'],'is_order'=>2]);
        if (!$wingingArr) $this->error('中奖信息错误');

        GroupWinning::updateAll(['is_order'=>3],['id'=>$arr['winning_id']]);

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $arr['amount']  = $data['money_up'];
            $arr['type']    = 3;
            $arr['period']  = $data['period'];
            $tradeOrder = new TradeOrder;
            //创建订单
            $orderId     =  $tradeOrder->addData($arr,$this->_member);
            if(!$orderId) throw new \Exception("订单创建失败");

            $wheres ="source_id=".$wingingArr['group_detail_id']." and member_id=".$this->_memberId." and source_type=6 and is_await=1";

            $balanceLog  = BalanceLog::updateAll(['is_await'=>0],$wheres);

            //增加合同钱包
            $re = Balance::addBalance($arr['member_id'],3,$arr['amount'],5,$orderId);
            if (isset($re['state']) && $re['state']==false) throw new \Exception($re['msg']);

            /*修改中奖表数据*/
            GroupWinning::updateAll(['is_order'=>1],'id='.$arr['winning_id']);

            $transaction->commit();

            //触发后续
            $params              = array();
            $params['money']     = $arr['amount'];
            $params['member_id'] = $this->_memberId;
            $params['source_id'] = 1;
            $params['mch_id']    = 0;
            $params['trigger_type'] = 1;
            $params['desc']         = 'from 【'.$this->_member['member_name'].'】';
            $params['order_type']   = $data['type'];
            $params['period']       = $arr['period']??0;
            $params['day_income']   = $data['day_income'];
            $params['commodity_id'] = $arr['goods_id'];
            BaseBonus::bonusRun($params);
            $this->out('签约成功');
        }catch (\Exception $e){
            $transaction->rollback();
            $this->error($e->getMessage());
        }
    }


    /*调试*/
    public function actionGroupDispose()
    {

        //查询出当天那些人中奖 那些人入围
        $where = 'group_time="' . date('Y-m-d', time()) . '" and status=1';
        $data = GroupDetail::getAll($where);

        $model = new GroupDetail();
        if (!$data) throw new \Exception('没有需要结算的活动');
        /*未中奖人员处理数据*/
        $model->finalist($data);
    }

}